import React, { useState, useEffect } from 'react';
import {
    Table,
    Button,
    Modal,
    Form,
    Input,
    Select,
    message,
    Space,
    Popconfirm,
    Tag
} from 'antd';
import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    LockOutlined,
    SearchOutlined
} from '@ant-design/icons';

const { Option } = Select;

const UserManagementPage = () => {
    const [users, setUsers] = useState([]);
    const [form] = Form.useForm();
    const [visible, setVisible] = useState(false);
    const [modalTitle, setModalTitle] = useState('新建用户');
    const [currentId, setCurrentId] = useState(null);
    const [searchValue, setSearchValue] = useState('');

    // 修改密码的状态
    const [passwordModalVisible, setPasswordModalVisible] = useState(false);
    const [passwordForm] = Form.useForm();
    const [passwordUser, setPasswordUser] = useState(null);

    useEffect(() => {
        fetchUserData();
    }, []);

    const fetchUserData = () => {
        const mockUsers = [
            {
                id: 1,
                username: 'admin',
                phone: '13800000000',
                role: 'admin',
                createdAt: '2023-01-01'
            },
            {
                id: 2,
                username: 'user1',
                phone: '13800000001',
                role: 'user',
                createdAt: '2023-02-10'
            },
            {
                id: 3,
                username: 'editor',
                phone: '13800000002',
                role: 'editor',
                createdAt: '2023-03-15'
            }
        ];
        setUsers(mockUsers);
    };

    // 修改密码
    const handleChangePassword = (user) => {
        setPasswordUser(user);
        passwordForm.resetFields();
        setPasswordModalVisible(true);
    };

    const handleDelete = (userId) => {
        console.log('Delete user with id:', userId);
        message.success('用户已删除');
        setUsers(users.filter(user => user.id !== userId));
    };

    const handleEdit = (id) => {
        const user = users.find(u => u.id === id);
        if (user) {
            form.setFieldsValue(user);
            setModalTitle('编辑用户');
            setCurrentId(id);
            setVisible(true);
        }
    };

    const handleCreate = () => {
        setModalTitle('新建用户');
        setCurrentId(null);
        form.resetFields();
        setVisible(true);
    };

    const handleFormSubmit = (values) => {
        if (currentId) {
            const updatedUsers = users.map(user =>
                user.id === currentId ? { ...user, ...values } : user
            );
            setUsers(updatedUsers);
            message.success('用户信息已更新');
        } else {
            const newUser = {
                ...values,
                id: users.length + 1,
                createdAt: new Date().toISOString().split('T')[0]
            };
            setUsers([...users, newUser]);
            message.success('用户创建成功');
        }
        setVisible(false);
    };

    const roleToTag = (role) => {
        switch (role) {
            case 'admin':
                return <Tag color="red">管理员</Tag>;
            case 'editor':
                return <Tag color="blue">编辑</Tag>;
            case 'user':
            default:
                return <Tag color="green">用户</Tag>;
        }
    };

    const columns = [
        { title: '用户名', dataIndex: 'username', key: 'username' },
        { title: '手机号', dataIndex: 'phone', key: 'phone' },
        { title: '角色', dataIndex: 'role', key: 'role', render: roleToTag },
        { title: '创建时间', dataIndex: 'createdAt', key: 'createdAt' },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button
                        icon={<EditOutlined />}
                        onClick={() => handleEdit(record.id)}
                        style={{ padding: '0 8px' }}
                    />
                    <Button
                        icon={<LockOutlined />}
                        onClick={() => handleChangePassword(record)}
                        style={{ padding: '0 8px' }}
                    />
                    <Popconfirm
                        title="确定要删除这个用户吗?"
                        onConfirm={() => handleDelete(record.id)}
                        okText="是"
                        cancelText="否"
                    >
                        <Button
                            danger
                            icon={<DeleteOutlined />}
                            style={{ padding: '0 8px' }}
                        />
                    </Popconfirm>
                </Space>
            )
        }
    ];

    const handleSearch = (value) => {
        setSearchValue(value);
    };

    const filteredUsers = users.filter(user =>
        user.username.includes(searchValue) || user.phone.includes(searchValue)
    );

    return (
        <div style={{ padding: '20px' }}>
            <div style={{ marginBottom: '20px' }}>
                <h1 style={{ margin: 0, marginBottom: '20px' }}>用户管理</h1>
                <Space>
                    <Input
                        placeholder="请输入用户名或手机号搜索"
                        prefix={<SearchOutlined />}
                        value={searchValue}
                        onChange={(e) => handleSearch(e.target.value)}
                        style={{ width: '300px' }}
                    />
                    <Button
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={handleCreate}
                    >
                        新建用户
                    </Button>
                </Space>
            </div>

            <Table
                columns={columns}
                dataSource={filteredUsers}
                pagination={{ pageSize: 5 }}
                rowKey="id"
            />

            {/* 创建/编辑用户弹窗 */}
            <Modal
                title={modalTitle}
                open={visible}
                onCancel={() => setVisible(false)}
                footer={null}
            >
                <Form
                    form={form}
                    layout="vertical"
                    onFinish={handleFormSubmit}
                >
                    <Form.Item
                        name="username"
                        label="用户名"
                        rules={[{ required: true, message: '请输入用户名!' }]}
                    >
                        <Input placeholder="请输入用户名" />
                    </Form.Item>

                    <Form.Item
                        name="phone"
                        label="手机号"
                        rules={[
                            { required: true, message: '请输入手机号!' },
                            { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号!' }
                        ]}
                    >
                        <Input placeholder="请输入手机号" />
                    </Form.Item>

                    <Form.Item
                        name="role"
                        label="角色"
                        rules={[{ required: true, message: '请选择用户角色!' }]}
                    >
                        <Select placeholder="请选择角色">
                            <Option value="admin">管理员</Option>
                            <Option value="editor">编辑</Option>
                            <Option value="user">普通用户</Option>
                        </Select>
                    </Form.Item>

                    {!currentId && (
                        <>
                            <Form.Item
                                name="password"
                                label="密码"
                                rules={[{ required: true, message: '请输入密码!' }]}
                            >
                                <Input.Password placeholder="请输入密码" />
                            </Form.Item>
                            <Form.Item
                                name="confirmPassword"
                                label="确认密码"
                                dependencies={['password']}
                                hasFeedback
                                rules={[
                                    { required: true, message: '请再次输入密码!' },
                                    ({ getFieldValue }) => ({
                                        validator(_, value) {
                                            if (!value || getFieldValue('password') === value) {
                                                return Promise.resolve();
                                            }
                                            return Promise.reject(new Error('两次输入的密码不一致'));
                                        }
                                    })
                                ]}
                            >
                                <Input.Password placeholder="请再次输入密码" />
                            </Form.Item>
                        </>
                    )}

                    <Form.Item>
                        <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
                            {currentId ? '更新用户' : '创建用户'}
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>

            {/* 修改密码弹窗 */}
            <Modal
                title={`修改密码 - ${passwordUser?.username || ''}`}
                open={passwordModalVisible}
                onCancel={() => setPasswordModalVisible(false)}
                footer={null}
            >
                <Form
                    form={passwordForm}
                    onFinish={(values) => {
                        console.log('Change password for', passwordUser, values);
                        message.success('密码修改成功');
                        setPasswordModalVisible(false);
                    }}
                >
                    <Form.Item
                        name="password"
                        label="新密码"
                        rules={[{ required: true, message: '请输入新密码!' }]}
                    >
                        <Input.Password />
                    </Form.Item>
                    <Form.Item
                        name="confirmPassword"
                        label="确认密码"
                        dependencies={['password']}
                        hasFeedback
                        rules={[
                            { required: true, message: '请再次输入密码!' },
                            ({ getFieldValue }) => ({
                                validator(_, value) {
                                    if (!value || getFieldValue('password') === value) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error('两次输入的密码不一致'));
                                }
                            })
                        ]}
                    >
                        <Input.Password />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">修改密码</Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default UserManagementPage;
